package com.netdisk.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.netdisk.dao.Dao;
import com.netdisk.entity.GroupsUsers;

@Repository(value = "groupsUsersDao")
public class GroupsUsersDao extends Dao<GroupsUsers> {

	@Override
	public void save(GroupsUsers obj) {
		Session session = sessionFactory.getCurrentSession();
		session.save(obj);
	}

	@Override
	public void update(GroupsUsers obj) {
		Session session = sessionFactory.getCurrentSession();
		session.update(obj);

	}

	@Override
	public void delete(GroupsUsers obj) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(obj);
	}

	@Override
	public List<GroupsUsers> findAll() {
		Session session = sessionFactory.getCurrentSession();
		List<GroupsUsers> groupsUsers = null;
		groupsUsers = session.createQuery("from GroupsUsers").list();
		return groupsUsers;
	}

	/***
	 * @see findById(long companyId, long groupId) 双主键 ,不提供此方法
	 */
	@Override
	public GroupsUsers findById(String id) {
		throw new UnsupportedOperationException();
	}

	public GroupsUsers findById(long groupId, long userId) {
		Session session = sessionFactory.getCurrentSession();
		List<GroupsUsers> groupsUsers = null;
		GroupsUsers group = null;
		Query query = session
				.createQuery("from GroupsUsers where groupId=:groupId"
						+ " and userId=:userId");
		query.setLong("groupId", groupId);
		query.setLong("userId", userId);
		groupsUsers = query.list();

		if (!groupsUsers.isEmpty()) {
			group = groupsUsers.get(0);
		}
		return group;
	}
	public List<GroupsUsers> findByGroupId(long groupId) {
		Session session = sessionFactory.getCurrentSession();
		List<GroupsUsers> groupsUsers = null;
		Query query = session
				.createQuery("from GroupsUsers where groupId=:groupId");
		query.setLong("groupId", groupId);
		groupsUsers = query.list();
		return groupsUsers;
	}
	public List<GroupsUsers> findByUserId(long userId) {
		Session session = sessionFactory.getCurrentSession();
		List<GroupsUsers> groupsUsers = null;
		Query query = session
				.createQuery("from GroupsUsers where userId=:userId");
		query.setLong("userId", userId);
		groupsUsers = query.list();
		return groupsUsers;
	}

	@Override
	public List<GroupsUsers> findByTop(int from, int max) {
		Session session = sessionFactory.getCurrentSession();
		List<GroupsUsers> groupsUsers = null;
		Query query = session.createQuery("from GroupsUsers");
		query.setFirstResult(from);
		query.setMaxResults(max);
		groupsUsers = query.list();
		return groupsUsers;
	}

}
